package com.tgy.基础学习.Thread.Normal;

import lombok.SneakyThrows;

import java.util.Objects;

/**
 * @author 送你一块二向箔
 * @date 2021/11/06 19:25
 *
 * 模拟龟兔赛跑
 *
 */
public class Race implements Runnable{
    private static String winner;

    @SneakyThrows
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            //模拟兔子休息
            if (Objects.equals(Thread.currentThread().getName(),"兔子") && i %10 == 0) {
                Thread.sleep(1);
            }

            //判断比赛是否结束
            boolean flag = gameOver(i);
            if(flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+""+i+"步");
        }
    }

    private boolean gameOver(int step){
        if(!Objects.equals(winner,null)){//已经存在胜利者
            return true;
        }{
            if(step == 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner is "+winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}
